package com.zzyl.framework.interceptor;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.UserThreadLocal;
import com.zzyl.framework.web.service.TokenService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class MemberInterceptor implements HandlerInterceptor {
    @Autowired
    private TokenService tokenService;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 首先校验是否是controller层的请求,不是直接放行
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        //2. 获取到token
        String token = request.getHeader("Authorization");
        //3. 校验token,如果token为空，响应401，重新登录
        if(StringUtils.isEmpty( token)){
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            AjaxResult ajaxResult = AjaxResult.error(401,"请重新登录！");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }
        //解析token，拿到其中的数据
        Claims claims = tokenService.parseToken(token);
        if(ObjectUtil.isEmpty( claims)){
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            AjaxResult ajaxResult = AjaxResult.error(401,"请重新登录！");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }
        //如果有数据，解析token中的数据
        Long userId = MapUtil.get(claims,"userId",Long.class);
        if (ObjectUtil.isEmpty(userId)){
            response.setContentType("application/json;charset=UTF-8");
            response.setStatus(401);
            AjaxResult ajaxResult = AjaxResult.error(401,"请重新登录！");
            response.getWriter().write(JSONUtil.toJsonStr(ajaxResult));
            return false;
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserThreadLocal.remove();
    }
}
